package de.yellowshoes.tedx.net;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;

import com.j256.ormlite.dao.RuntimeExceptionDao;

import de.yellowshoes.tedx.TEDxConstants;
import de.yellowshoes.tedx.helper.DateHelper;
import de.yellowshoes.tedx.net.exception.CsvReaderException;
import de.yellowshoes.tedx.persistence.PersistenceHelper;
import de.yellowshoes.tedx.persistence.entity.Agenda;
import de.yellowshoes.tedx.persistence.entity.Speaker;

/**
 * Reads speaker infos from a csv file.
 * 
 * @author calibanatspace
 * 
 */
public class AgendaReader
    {
    private String            url = null;
    private PersistenceHelper db  = null;

    public AgendaReader( String url, PersistenceHelper db )
        {
        this.url = url;
        this.db = db;
        }

    public List< Agenda > read() throws ParseException
        {
        CsvRemoteReader reader = new CsvRemoteReader( url, ";", 7 );
        List< Object[] > objectList = null;
        List< Agenda > agendaList = new ArrayList< Agenda >();

        try
            {
            objectList = reader.read();
            }
        catch( CsvReaderException e )
            {
            Log.e( TEDxConstants.LOG_TAG, "Error while reading speakers.csv via url " + url, e );
            return null;
            }

        if( objectList.size() > 0 )
            {
            objectList.remove( 0 );
            }

        DateHelper dateHelper = new DateHelper();

        for( Object[] objects : objectList )
            {
            if( objects.length > 6 )
                {
                Agenda agenda = new Agenda();
                agenda.setTitle( ( String )objects[ 0 ] );
                agenda.setShortDescription( ( String )objects[ 1 ] );
                agenda.setDescription( ( String )objects[ 2 ] );
                agenda.setStartTime( dateHelper.parseCsvStringToDate( ( String )objects[ 3 ] ) );
                agenda.setEndTime( dateHelper.parseCsvStringToDate( ( String )objects[ 4 ] ) );
                agenda.setPause( Boolean.parseBoolean( ( ( String )objects[ 5 ] ).toLowerCase() ) );
                agenda.setSpeaker( getSpeakerFromText( ( String )objects[ 6 ] ) );

                agendaList.add( agenda );
                }
            }

        return agendaList;
        }

    private Speaker getSpeakerFromText( String text )
        {
        if( db != null && text != null )
            {
            RuntimeExceptionDao< Speaker, String > dao = db.getSpeakerDao();

            if( dao.idExists( text ) == true )
                {
                return dao.queryForId( text );
                }
            }

        return null;
        }
    }
